import { getToken, removeToken, setToken } from '@/utils/auth'
import { getInfo, login, logout, register, validate } from '@/api/user';
import router from '@/router'

const state = {
    token: getToken(),
    userId: '',
    name: '',
    avatar: '',
    introduction: ''
}
const mutations = {
    SET_TOKEN: (state, token) => {
        state.token = token
    },
    SET_INTRODUCTION: (state, introduction) => {
        state.introduction = introduction
    },
    SET_ID: (state, userId) => {
        state.userId = userId
    },
    SET_NAME: (state, name) => {
        state.name = name
    },
    SET_AVATAR: (state, avatar) => {
        state.avatar = avatar
    }
}

const actions = {
    async validate ({ commit }) {
        const res = await validate()
        if (res.code === 200) {
            const parse = JSON.parse(res.data);
            commit('SET_TOKEN', parse.token)
        }
        return state.token
    },
    // user login
    login ({ commit }, userInfo) {
        const { username, password } = userInfo
        return new Promise((resolve, reject) => {
            login({ username: username.trim(), password: password }).then(response => {
                const res = response
                // console.log(res)
                if (res.code !== 200) {
                    reject(new Error())
                }
                const data = JSON.parse(res.data);
                console.log(data.token)
                const { id, username, avatar } = data.user

                // roles must be a non-empty array
                if (!username) {
                    reject(new Error('用户名不能为空！'))
                }
                commit('SET_ID', id)
                commit('SET_NAME', username)
                commit('SET_AVATAR', avatar)
                commit('SET_TOKEN', data.token)
                setToken(data.token)
                resolve()
            }).catch(error => {
                reject(error)
            })
        })
    },
    // user register
    register ({ commit }, userInfo) {
        const { userName, realName, password } = userInfo
        return new Promise((resolve, reject) => {
            register({ userName: userName.trim(), realName: realName.trim(), password: password }).then(response => {
                const res = response
                if (res.code !== 200) {
                    reject(new Error())
                }
                const data = JSON.parse(res.data);
                commit('SET_TOKEN', data.token)
                setToken(data.token)
                resolve()
            }).catch(error => {
                reject(error)
            })
        })
    },

    // get user info
    getInfo ({ commit, state }) {
        return new Promise((resolve, reject) => {
            getInfo().then(response => {
                const { data } = response

                if (!data) {
                    reject(new Error('校验失败，请重新登录！'))
                }

                const { id, roles, userName, avatar } = data

                // roles must be a non-empty array
                if (!roles || roles.length <= 0) {
                    reject(new Error('用户角色不能为空！'))
                }
                commit('SET_ID', id)
                commit('SET_NAME', userName)
                commit('SET_AVATAR', avatar)
                resolve(data)
            }).catch(error => {
                reject(error)
            })
        })
    },

    // user logout
    logout ({ commit, state, dispatch }) {
        return new Promise((resolve, reject) => {
            logout(state.token).then(() => {
                commit('SET_TOKEN', '')
                removeToken()
                // reset visited views and cached views
                // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
                // dispatch('tagsView/delAllViews', null, { root: true })
                resolve()
            }).catch(error => {
                reject(error)
            })
        })
    },

    // remove token
    resetToken ({ commit }) {
        return new Promise(resolve => {
            commit('SET_TOKEN', '')
            removeToken()
            resolve()
        })
    },

    // dynamically modify permissions
    async changeRoles ({ commit, dispatch }, role) {
        const token = role + '-token'
        commit('SET_TOKEN', token)
        setToken(token)
        const { roles } = await dispatch('getInfo')
        // generate accessible routes map based on roles
        const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
        // dynamically add accessible routes
        router.addRoutes(accessRoutes)
        // reset visited views and cached views
        // dispatch('tagsView/delAllViews', null, { root: true })
    }
}

export default {
    namespaced: true,
    state,
    mutations,
    actions
}
